package 典型.操作系统;

import java.util.UUID;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Product {
    int num = 0;
    int max = 10;
    String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
    ReentrantLock lock = new ReentrantLock();
    Condition c = lock.newCondition();
    Semaphore s = new Semaphore(10);

    @Override
    public String toString() {
        return "Product{" +
                "num=" + num +
                ", uuid='" + uuid + '\'' +
                '}';
    }

    public String toString2() {
        return "Product{" +
                "num=" + s.getQueueLength() +
                ", uuid='" + uuid + '\'' +
                '}';
    }

    synchronized public void consume() throws InterruptedException {
        if (num == 0) {
            wait();
        } else {
            System.out.println(this + "被消费了");
            this.num--;
            notify();
        }
    }

    public void consume2() throws InterruptedException {
        s.acquire();
        System.out.println(this.toString2() + "被消费了");
    }

    synchronized public void provide() throws InterruptedException {
        if (num == max) {
            wait();
        } else {
            System.out.println(this + "成产出来了");
            this.num++;
            notify();
        }
    }

    public void provide2() throws InterruptedException {
        s.release();
        System.out.println(this.toString2() + "生产出来了");
    }


}
